﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

using Microsoft.AspNetCore.Mvc;

/// <summary>
/// 全局异常错误日志
/// </summary>
public class GlobalExceptionsFilter : IExceptionFilter
{
    private readonly IWebHostEnvironment _env;
    private readonly ILoggerHelper _loggerHelper;
    /// <summary>
    /// 全局异常过滤
    /// </summary>
    /// <param name="env"></param>
    /// <param name="loggerHelper"></param>
    public GlobalExceptionsFilter(IWebHostEnvironment env, ILoggerHelper loggerHelper)
    {
        _env = env;
        _loggerHelper = loggerHelper;
    }

    /// <summary>
    /// 异常事件处理
    /// </summary>
    /// <param name="context"></param>
    public void OnException(ExceptionContext context)
    {
        var json = new JsonErrorResponse();
        json.Message = context.Exception.Message;//错误信息
        if (_env.IsDevelopment())
        {
            json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息
        }
        context.Result = new InternalServerErrorObjectResult(json);

        //采用log4net 进行错误日志记录
        _loggerHelper.Error(json.Message, WriteLog(json.Message, context.Exception));

    }

    /// <summary>
    /// 自定义返回格式
    /// </summary>
    /// <param name="throwMsg"></param>
    /// <param name="ex"></param>
    /// <returns></returns>
    public string WriteLog(string throwMsg, Exception ex)
    {
        if (ex == null)
        {
            return string.Format("【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}",
                throwMsg, "N/A", "N/A", "N/A");
        }
        else
        {
            return string.Format("【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}",
                throwMsg, ex.GetType().Name, ex.Message, ex.StackTrace);
        }
    }


}
/// <summary>
/// 错误收集
/// </summary>
public class InternalServerErrorObjectResult : ObjectResult
{
    /// <summary>
    /// 错误收集
    /// </summary>
    /// <param name="value"></param>
    public InternalServerErrorObjectResult(object value) : base(value)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }
}
/// <summary>
/// 返回错误信息
/// </summary>
public class JsonErrorResponse
{
    /// <summary>
    /// 生产环境的消息
    /// </summary>
    public string? Message { get; set; }
    /// <summary>
    /// 开发环境的消息
    /// </summary>
    public string? DevelopmentMessage { get; set; }
}